// 加载页面判断cookie，有cookie的话进入用户主页
$(function($) {


    if (getCookie('$flag') == '' && document.cookie != '') {
        let str = decodeURIComponent(document.cookie);
        console.log(str);
        // $('.log_Btn>a').text('')
        let arr = str.split('=');
        let newstr = arr[0].toString();
        $('.top_nav').children('li').eq(0).removeClass('log_Btn').addClass('user1').eq(0).text(newstr);
    }

})


// 登录弹出模态框

// js 实现点击手机号登录或邮箱登录实现表单切换

// 表单及时验证




// 窗口滚动事件
window.onscroll = function() {
        // 左侧导航条
        // console.log(document.documentElement.scrollTop);
        if (document.documentElement.scrollTop > 110) {
            $('.topslide_Nav').css('display', 'block');
        }
        if (document.documentElement.scrollTop < 110) {
            $('.topslide_Nav').css('display', 'none');
        }


    }
    // 人气推荐板块点击事件

// 登录链接后端接口

// 点击购物车事件
$(function($) {
        $('.cart_Btn').on('click', function() {
            // console.log(document.cookie);
            if (document.cookie == '') {
                top.location.href = "./login.html";

            } else {
                // console.log(2);
                top.location.href = "./gouwuche.html";
            }
        })
    })
    // 鼠标滑过顶部导航时出现二级菜单

$(function($) {
        $('.search_Button>li').eq(0).nextAll().on('mouseover', function() {
            $(this).children('.erJiCD').css('display', 'block');


        })
        $('.search_Button>li').eq(0).nextAll().on('mouseout', function() {
            $('.erJiCD').css('display', 'none');
        })

    })
    // 页面加载完成渲染二级菜单
$(function() {
        //   建立数据对象传参
        var dataObj = {
                "居家生活": {
                    "床品件套": "床品件套",
                    "被枕褥毯": "被枕盖毯,床垫床褥",
                    "办公家具": "办公家具,好物精选",
                    "卧室家具": "卧室家具,灯具,小件家具,北欧原木,浴室用品",
                    "厨房电器": "厨房电器,餐厨爆款清单",
                    "锅具清洁": "品质锅具,餐厨配件,刀剪砧板,餐具,水具杯壶,茶咖酒具,品茗茶具"

                },
                "宠物生活": {
                    "宠物主粮": "猫粮,犬粮",
                    "宠物零食": "宠物罐头,冻干零食"
                }
            }
            // 获取最大数量进行传参，建html结构
        function getKeyNum(obj) {
            let num = 0;
            for (x in obj) {
                num++;
            }
            return num;
        }
        // 写一个获取json对象KEY值的函数，以数组形式返回
        function getkey(obj) {
            let arr = [];
            for (x in obj) {
                // console.log(x);
                arr.push(x);
            }
            return arr;
        }
        // 获取对象的value,以二维数组形式返回
        function getvalue(obj) {
            let arr = [];
            for (x in obj) {
                // console.log(obj[x]);
                arr.push(obj[x].split(','));

            }
            return arr;
        }
        // 页面渲染
        $('.search_Button>li').eq(0).nextAll().each(function() {

            let topText = $(this).children('a').text();
            // console.log(topText);
            let liNum = getKeyNum(dataObj[topText]);

            let arr = getkey(dataObj[topText]);
            // console.log(arr);
            let erweiArr = getvalue(dataObj[topText]);
            // console.log(erweiArr);
            // console.log(liNum);
            for (let i = 0; i < liNum; i++) {
                $(this).children('.erJiCD').children('ul').append(`<li>${arr[i]}</li>`);
                $(this).children('.erJiCD').children('div').append("<ul></ul>")
            }

            let li = $(this).children('.erJiCD').children('div').children('ul');
            // console.log(li);
            let num = 0;
            li.each(function() {
                let xnum = 0;
                $.each(erweiArr[num], function() {
                    xnum++;
                });

                for (let i = 0; i < xnum; i++) {
                    $(this).append(`<li><div></div><span>${erweiArr[num][i]}</span></li>`)
                }

                num++;
            })
        })
    })
    // 顶部导航交互时，吸顶导航同时交互
$(function($) {

    })
    //
    // 请求数据库加载页面
    /*
$(function() {
        $.get("./goodsAndShoppingCart/getGoodsType.php", function(data) {
                // console.log(data);
                // console.log(JSON.parse(data));
                let jsondata = JSON.parse(data);
                let datanum = JSON.parse(data).length;
                for (let i = 0; i < datanum; i++) {
                    // console.log(jsondata[i]);
                    $(".all_fenlei").eq(0).append(`<li>${jsondata[i]['goodsType']}</li>`)
                    let $append =
                        $('#goods_show').clone(true).css('display', 'block').appendTo($('.bottom_all'));
                    $append.children('#title_top').text(`${jsondata[i]['goodsType']}`);
                    // 
                    // console.log(jsondata[i]['typeId']);
                    $.get("./goodsAndShoppingCart/getGoodsList.php", {
                        "typeId": `${jsondata[i]['typeId']}`
                    }, function(data) {
                        console.log(JSON.parse(data));

                        // JSON.parse(data)[num]['goodsName']
                        let Inum = 0;
                        $append.find('.view_box').each(function() {

                            $(this).children('img').attr({
                                src: `${JSON.parse(data)[Inum]["goodsImg"]}`,
                                alt: `${JSON.parse(data)[Inum]['goodsName']}`,
                                title: `${JSON.parse(data)[Inum]['goodsName']}`
                            })
                            $(this).children('#goods_name').children('span').text(`${JSON.parse(data)[Inum]['goodsName']}`)
                            $(this).children('#goods_price').text('￥' + `${JSON.parse(data)[Inum]['goodsPrice']}`)
                            $(this).children('#goods_info').text(`${JSON.parse(data)[Inum]['goodsDesc']}`)
                            Inum++;
                        });
                    })

                }  

                // let Inum = 0;
                // $(this).find("img").each(function() {
                //     $(this).eq(Inum).attr({ src: `${JSON.parse(data)[Inum]["goodsImg"]}`, alt: `${JSON.parse(data)[Inum]['goodsName']}`, title: `${JSON.parse(data)[Inum]['goodsName']}` })
                //     console.log(JSON.parse(data)[Inum]["goodsImg"]);
                //     Inum++;

                // })

                // 商品类型展示完成
                // 商品大纲展示


            })
            // $.get("./goodsAndShoppingCart/getGoodsList.php", { "typeId": "001" }, function(data) {
            //     console.log(data);
            // })
    })

    
    */


// $.get(“getGoodsList.php”,{“typeId”,001},function(data){

// });
// data:[
//     {
//         "typeId":"001",
//         "goodsType":"鞋"
// 	},
//     { 
//         "typeId":"002",
//         "goodsType":"衣服"
// 	}
// ]


// 放大镜
window.onload = function() {


        class Enlarge {
            constructor(ele) {
                this.box = ele;
                this.smallbox = ele.children[0];
                this.mask = ele.children[0].children[1];
                this.bigbox = ele.children[1];
                this.img = ele.children[1].children[0];
                this.bindEvents();
            }
            bindEvents() { //类方法
                    // 需要有鼠标移入,移出,鼠标移动,遮罩移动,大图移动;
                    //    鼠标移入smallbox时
                    this.smallbox.onmouseover = () => {
                            //   需要显示遮罩
                            this.show(); //遮罩显示

                            // 也需要显示bigbox
                            this.bigShow();

                        }
                        // 鼠标移出隐藏遮罩
                    this.smallbox.onmouseout = () => {
                            //   隐藏遮罩
                            this.hid();
                            // 隐藏bigbox
                            this.bigHid();
                        }
                        // 鼠标在smallbox中移动时候，遮罩跟随移动,此时bigbox中的img也需要同步移动.
                    this.smallbox.onmousemove = (e) => {
                        let ev = e || event;
                        let xnum = this.getAbsLeft(this.box);
                        let ynum = this.getAbsTop(this.box);

                        this.maskMove(ev, xnum, ynum);
                        // img同步移动函数
                        this.imgMove();


                    }

                }
                // 显示遮罩
            show() {
                    this.mask.style.display = 'block';
                }
                // 显示bigbox
            bigShow() {
                    this.bigbox.style.display = 'block';
                }
                // 隐藏遮罩
            hid() {

                    this.mask.style.display = 'none';
                }
                // 隐藏bigbox
            bigHid() {
                this.bigbox.style.display = 'none';
            }

            // 遮罩移动函数
            maskMove(ev, xnum, ynum) {

                    let x = ev.clientX - xnum - this.mask.offsetWidth / 2;

                    let y = ev.clientY - ynum - this.mask.offsetHeight / 2;
                    // console.log(y);
                    // 边界限制 
                    if (x <= 0) {
                        x = 0;
                    }
                    if (x >= (this.smallbox.offsetWidth - this.mask.offsetWidth)) {
                        x = (this.smallbox.offsetWidth - this.mask.offsetWidth);
                    }
                    if (y <= 0) {
                        y = 0;
                    }
                    if (y >= (this.smallbox.offsetHeight - this.mask.offsetHeight)) {
                        y = (this.smallbox.offsetHeight - this.mask.offsetHeight);
                    }


                    this.mask.style.left = x + 'px';
                    this.mask.style.top = y + 'px';
                }
                // 获取元素距离视口左边的距离
            getAbsLeft(obj) {
                var l = obj.offsetLeft;
                while (obj.offsetParent != null) {
                    obj = obj.offsetParent;
                    l += obj.offsetLeft;
                }
                return l;
            }
            getAbsTop(obj) {
                var l = obj.offsetTop;
                while (obj.offsetParent != null) {
                    obj = obj.offsetParent;
                    l += obj.offsetTop;
                }
                return l - document.documentElement.scrollTop;
            }


            // img移动函数
            imgMove() {
                let lvx = (this.img.clientWidth - this.bigbox.offsetWidth) / (this.smallbox.clientWidth - this.mask.offsetWidth);
                let lvy = (this.img.clientHeight - this.bigbox.offsetHeight) / (this.smallbox.clientHeight - this.mask.offsetHeight);


                this.img.style.left = -lvx * parseInt(this.mask.style.left) + 'px';
                this.img.style.top = -lvy * parseInt(this.mask.style.top) + 'px';

            }
        }
        let oBox = document.querySelector('#fangdajing');
        new Enlarge(oBox);
    }
    // 页面加载完成,渲染商品数据
$(function($) {
        let storage = window.localStorage;
        let goodsdataObj = JSON.parse(storage.getItem('goodsdata'));
        $('.fangdajin_body').children('img').attr("src", `${goodsdataObj['goodsImg']}`);
        $('.fangdajin_right').children('img').attr("src", `${goodsdataObj['goodsImg']}`);
        $('.img_box li:eq(0) img:eq(0)').attr("src", `${goodsdataObj['goodsImg']}`);
        // console.log($('.img_box li:eq(0) img:eq(0)'));
        $('.top_goodsName h4 span').text(`${goodsdataObj['goodsName']}`);
        $('.top_goodsName h5 span:eq(0)').text(`${goodsdataObj['goodsDesc']}`);
        $('#goodsPrice_change').text(`${goodsdataObj['goodsPrice'].slice(1)}`)
            // storage.clear('goodsdata');

        // 点击加入购物车
        $('#add_goodscart').on('click', function() {
                // 
                console.log(2);
                let str = decodeURIComponent(document.cookie);
                // console.log(str);
                let arr = str.split('=');
                let newstr = arr[0].toString();
                // 
                $.get("./goodsAndShoppingCart/addShoppingCart.php", { "vipName": `${newstr}`, "goodsId": `${goodsdataObj['goodsId']}`, "goodsCount": `${$('.goods_num').find('input').val()}` },
                    function(data) {
                        // console.log(1);
                        if (data == 1) {
                            $('.cart_Tag').text(parseInt($('.cart_Tag').text() + 1));
                            alert('成功');
                            location.reload();



                        } else if (data == 0) {
                            alert('添加失败');
                        } else {
                            alert('数据库链接失败');
                        }
                    })


            })
            // 增加减少
        $('#reduce').on('click', function() {
            if ($('.goods_num').find('input').val() > 1) {
                $('.goods_num').find('input').val($('.goods_num').find('input').val() - 1);
            }
        })
        $('#add').on('click', function() {
            if ($('.goods_num').find('input').val() < 99) {
                $('.goods_num').find('input').val(1 + parseInt($('.goods_num').find('input').val()));
            }
        })


    })
    // 点击加入购物车
    // $(function() {
    //     $('#add_goodscart').on('click', function() {
    //         $.get("./goodsAndShoppingCart/addShoppingCart.php"), { "vipName": }
    //             // $.get(“ addShoppingCart.php”,{“typeId”,001},function(data){

//         // });

//     })
// })

// 购物车
// 获取购物车数据库数据
$(function($) {
        if (document.cookie != '') {
            let str = decodeURIComponent(document.cookie);
            console.log(str);
            // $('.log_Btn>a').text('')
            let arr = str.split('=');
            let newstr = arr[0].toString();
            $.get("./goodsAndShoppingCart/getShoppingCart.php", { "vipName": `${newstr}` }, function(data) {
                    let goodsdata = JSON.parse(data); //json 数组对象形式
                    console.log(goodsdata);
                    let zongjia = 0;
                    let cart_Tag = 0;
                    for (let key in goodsdata) {
                        cart_Tag++;
                        let $div = $('#goods_box1').clone(true).appendTo($('.cart_body')).css('display', 'block');
                        $div.find('img').attr('src', `${ goodsdata[key]['goodsImg']}`);
                        $div.find('.goods_name1').text(`${ goodsdata[key]['goodsName'].slice(0,8) + '...'}`);
                        $div.find('.goods_price1').text('￥' + `${ goodsdata[key]['goodsPrice']}`);
                        $div.find('.goodsDesc1').text(`${ goodsdata[key]['goodsDesc'].slice(0,8) + '...'}`);
                        $div.find('.goods_num1').text('x' + `${ goodsdata[key]['goodsCount']}`);
                        $div.find('b').attr('index', `${ goodsdata[key]['goodsId']}`);
                        zongjia += goodsdata[key]['goodsPrice'] * goodsdata[key]['goodsCount'];
                    }
                    $('.cart_Tag').text(cart_Tag);
                    $('#zongjia').text('￥' + zongjia);

                })
                // 鼠标滑过购物车,显示商品
            $('.cart_Btn').hover(function() {
                $('.small_cart').css('display', 'block')
            }, function() {
                $('.small_cart').css('display', 'none')
            });

            // 点x删除购物车数据库商品
            $('.goods_info1').find('b').on('click', function() {
                    console.log(321);
                    let $this = $(this);
                    $.get("./goodsAndShoppingCart/deleteGoods.php", { 'vipName': `${newstr}`, 'goodsId': `${$(this).attr('index')}` }, (data) => {
                        if (data == 1) {
                            $('.cart_Tag').text(parseInt($('.cart_Tag').text() - 1));
                            $this.parents('#goods_box1').css('display', 'none');
                            alert('删除成功');


                        } else {
                            alert('删除失败');
                        }
                    });

                })
                // 点击去购物车结算
            $('.goodscart_btn1').on('click', function() {
                top.location.href = "./gouwuche.html";
            })
        }


    })
    // 阻止购物车事件冒泡
$(function() {
        $('.small_cart').on('click', function(e) {
            e.stopPropagation();
        })

    })
    // .stopPropagation();


// 点击购物车商品，跳转到商品详情页面
$(function() {
    $('.goods_name1').on('click', function() {
        console.log(333);
        let $goodsId = $(this).nextAll('b').attr('index');
        $.get("./goodsAndShoppingCart/getGoodsInfo.php", { "goodsId": `${$goodsId}` }, function(data) {
            let gdata = JSON.parse(data);
            console.log(gdata);
            let d = JSON.stringify(gdata);
            let storage = window.localStorage;
            storage.setItem("goodsdata", d);
            top.location.href = "./goodsInfo.html";

        });
        // let gdata = {
        //     goodsId: `${$(this).attr('index')}`,
        //     goodsName: `${$(this).find('#goods_name').children('span').text()}`,
        //     goodsPrice: `${$(this).find('#goods_price').text()}`,
        //     goodsInfo: `${$(this).find('#goods_info').text()}`,
        //     goodsImg: `${$(this).find('img').attr('src')}`
        // }
        // let d = JSON.stringify(gdata);
        // let storage = window.localStorage;
        // storage.setItem("goodsdata", d);
        // top.location.href = "./goodsInfo.html";
    })
})